
import {
	showToast
}from '@/utils/asyncUni.js'

let access_token = ''
let ref_token = ''
let refreshNow = false
export function request(config,forbidHUD) {
		
		
	//写法二   导出函数体
	let tokenObj = uni.getStorageSync('token')
	
	access_token = tokenObj?tokenObj.access_token:''
	ref_token = tokenObj?tokenObj.refresh_token:''
	
	// console.log(access_token)
	
	// // #ifdef APP-PLUS
	// console.log(USERObjectForKey('access_token'))
	// access_token = USERObjectForKey('access_token')
	// // #endif					

	return new Promise((resolve, reject) => {
		console.log(forbidHUD,'forbidHUD11111111')
		
		//接收是false或者undefine的时候 转圈
		if(forbidHUD == false){
			uni.showLoading({
				title: '加载中..',
				mask: true		
			})
		}else{ //是true的时候禁止转圈
			
		}
		let lastTime=uni.getStorageSync('lastTime') || 0
		
		
		let now=parseInt(new Date().getTime()/1000)
			
		if((now - lastTime > 7000) && lastTime!=0){
			console.error('刷新token')
			refreshToken(resolve, reject,config)
		}else{
			// console.log(config)
			uni.request({
				url: config.url,
				method: config.method || 'GET',
				data: config.data,
				header: {
					'token': access_token,
					'content-type': 'application/json; charset=utf-8',  // 明确指定请求头的编码为 UTF-8
				},

				success: (res) => {
					//
					let dataDic = res.data
					console.log(res)			
					if(typeof(res.data) == 'object'){
												
						if(dataDic.code == 1001){//						
							resolve(res.data)
						}else if(dataDic.code == 1003){//token失效							
							refreshToken(resolve, reject,config)
						}else{
							resolve(res.data)
						}
						
						// if(dataDic.code == 1002){//token不能存在了
						// 	//这里还没有写清空本地缓存的数据, 以后再写吧, 不影响使用						
						// 	uni.reLaunch({
						// 		url: '/pages/passport/login'
						// 	})
						// }else if(dataDic.code == 1003){//token失效
						// 	refreshToken(resolve, reject,config)
						// }												
						
					}else{						
						showToast("服务器网络异常")						
					}
										
					if(forbidHUD == false || !forbidHUD){
						uni.hideLoading()
					}		
										
					// uni.hideLoading()
					// setTimeout(()=>{
					// 	uni.hideLoading()
					// 	console.log('定时器延迟执行')
					// },2000)
					
				},
				fail: (error) => {
					console.log(error)
					
					reject(error)
					uni.hideLoading()
					uni.stopPullDownRefresh()
					showToast("服务器网络异常")
				}
			})
		}
	})
}



function refreshToken(resolve, reject,config){
	console.warn(config,'token失效了啊')
	
	if(refreshNow){
		console.log('已经去重置了,别添乱了啊😄')
		return
	}
	
	refreshNow = true
	
	uni.request({
		url: process.env.VUE_APP_BasePublic + '/h5/ref_token',
		method: 'POST',
		data: {
			ref_token
		},
		header: {
			'token': access_token
		},
		success: (res1) => {
			
			refreshNow = false
						
			console.error(res1)
									
			let updateTime=parseInt(new Date().getTime()/1000)						
			uni.getStorageSync('lastTime',updateTime.toString())
							
			
			// #ifdef APP-PLUS
			USERSetObjectForKey('lastTime',updateTime.toString())			
			// #endif
			if(res1.data.code == 1001){									
				uni.getStorageSync('token',res1.data.data)
				// #ifdef APP-PLUS
				USERSetObjectForKey('access_token',res1.data.data.access_token)
				USERSetObjectForKey('refresh_token',res1.data.data.refresh_token)				
				USERSetObjectForKey('token',JSON.stringify(res1.data.data))				
				USERSetObjectForKey('user', JSON.stringify(res1.data.user))					
				// #endif												
								
				uni.request({
					url: config.url,
					method: config.method || 'GET',
					data: config.data,
					header: {
						'token': res1.data.data.access_token
					},
					success: (res) => {
						console.log(res)
						resolve(res.data)
						uni.hideLoading()
					},
					fail: (error) => {
						// reject(error)
						uni.hideLoading()
					}
				})
			
			}else{
				uni.hideLoading()
				uni.reLaunch({
					url: '/pages/passport/login'
				})
				
			}
	
		},
		fail: (error) => {
			// reject(error)
			// console.log(error)
			refreshNow = false			
			showToast("服务器网络异常")
			uni.hideLoading()
		}
	})
}


export function USERSetObjectForKey(key, value) {
	if (typeof value != 'undefined' && typeof key === "string") {
		var UserDefaultsClass = plus.ios.importClass("NSUserDefaults");
		var standardUserDefaults = UserDefaultsClass.standardUserDefaults();
		plus.ios.invoke(standardUserDefaults, "setObject:forKey:", value, key);
		plus.ios.invoke(standardUserDefaults, "synchronize");
	}
}

export function USERObjectForKey(key) {
	if (typeof key != 'undefined' && typeof key === "string") {
		var UserDefaultsClass = plus.ios.importClass("NSUserDefaults");
		var standardUserDefaults = UserDefaultsClass.standardUserDefaults();
		return plus.ios.invoke(standardUserDefaults, "objectForKey:", key);
	}
	return null;
}

export function USERSetBoolForKey(key, value) {
	if (typeof value != 'undefined' && typeof key === "string") {
		var UserDefaultsClass = plus.ios.importClass("NSUserDefaults");
		var standardUserDefaults = UserDefaultsClass.standardUserDefaults();
		plus.ios.invoke(standardUserDefaults, "setBool:forKey:", value, key);
		plus.ios.invoke(standardUserDefaults, "synchronize");
	}
}

export function USERBoolForKey(key) {
	if (typeof key != 'undefined' && typeof key === "string") {
		var UserDefaultsClass = plus.ios.importClass("NSUserDefaults");
		var standardUserDefaults = UserDefaultsClass.standardUserDefaults();
		return plus.ios.invoke(standardUserDefaults, "boolForKey:", key);
	}
	return null;
}
export function USERRemoveForKey(key){
	
	if (typeof key != 'undefined' && typeof key === "string") {
		var UserDefaultsClass = plus.ios.importClass("NSUserDefaults");
		var standardUserDefaults = UserDefaultsClass.standardUserDefaults();
		plus.ios.invoke(standardUserDefaults, "removeObjectForKey:", key);
		plus.ios.invoke(standardUserDefaults, "synchronize");
		
	}
	return null;
	
}